<template>
  <div class="container">
    <div class="input">
      <h2>请输入视频链接</h2>
      <el-input
        placeholder="请输入url"
        v-model="url"
        @keyup.enter.native="handleEnterKey"
      ></el-input>
      <el-button type="primary" @click="handleEnterKey">开始拉流</el-button>
      <video
        id="webrtc"
        ref="webrtc"
        controls
        style="width: 50%; height: 50%; object-fit: fill"
      ></video>
    </div>
  </div>
</template>
<script>

//import JSWebrtc from "../../../public/jswebrtc.min.js";
// import JSWebrtc from "jswebrtc";
export default {
  data() {
    return {
      input: "",
      //webrtc://osiii.com/live/livestream
      url: "",
      player: null, //存储播放器实例
    };
  },
  methods: {
    // handleEnterKey() {
    //   console.log(`url:${this.url}`);
    //   //console.log(`input:${this.input}`);
    //   if (this.input) {
    //     this.url = this.input;
    //     this.initVideo(this.url);
    //   }
    // },
      handleEnterKey() {
       console.log('url:', this.url);
        if (this.url) {
          this.initVideo(this.url);
               }
      },
    // 初始化视频播放器
    initVideo(url) {
      // 如果播放器已存在，销毁之前的播放器
      if (this.player) {
        this.player.destroy();
        this.player = null;
      }

      const videoDom = this.$refs.webrtc; // 获取 video 元素的引用
      const JSWebrtc = window.JSWebrtc; // 从全局对象中获取 JSWebrtc
      // 初始化新的播放器
      this.player = new JSWebrtc.Player(url, {
        video: videoDom,
        autoplay: true,
        onPlay: () => {
          // 监听 canplay 事件，当视频可以播放时开始播放
          videoDom.addEventListener("canplay", function handleCanPlay() {
            videoDom.play();
            videoDom.removeEventListener("canplay", handleCanPlay); // 移除事件监听器，防止多次绑定
          });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  .input {
    box-sizing: border-box;
    text-align: center;
    /deep/.el-input__inner {
      width: 50%;
      background: #494141;
      color: #fff;
    }
  }
}
</style>
